<!-- 表单 》 评分 -->

<template>
  <el-form-item v-bind="formItem">
    <!-- 隐藏输入框，触发校验 -->
    <el-input v-show="false" :value="model" />

    <!-- 标签 -->
    <template v-if="hasLabelSlot" #label>
      <slot name="label" :label="formItem.label">{{ formItem.label }}</slot>
    </template>

    <el-rate v-model="model" v-bind="rateProps" @change="emitChange" />
  </el-form-item>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import mixForm from '../mixForm'

const name = 'FormRate'

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name,

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [mixForm],

  /**
   * 属性注册 (抽取以便查阅)
   */
  props: CORE.WEB[name],

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 评分属性
     */
    rateProps() {
      const { className, placeholder, size, max, allowHalf, showScore, showText } = this
      const maxStr = ` ${className}-${max}`
      const scoreStr = showScore ? ` ${className}-showScore` : ''
      const textStr = showText ? ` ${className}-showText` : ''
      return {
        'disabled-void-icon-class': 'el-icon-star-off',
        ...this.elProps,
        name: this.prop,
        class: `${className}${maxStr}${scoreStr}${textStr}`,
        disabled: this.isDisabled,
        clearable: !this.noClear,
        placeholder,
        size,
        texts: this.dict.map(([, name]) => name),
        max,
        allowHalf,
        showScore,
        showText,
      }
    },

    /**
     * 有效数值列表
     */
    validValues() {
      const { max, allowHalf } = this
      if (!allowHalf) return Array(max).fill().map((_, i) => i + 1)
      return Array(max * 2).fill().map((_, i) => (i + 1) * 0.5)
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 是否不等 (可覆盖)
     */
    isDiff() {
      const { obj, prop, model } = this
      const value = obj[prop]
      if (value === '') return model
      return value !== `${model}`
    },

    /**
     * 设置内部绑定值 (可覆盖)
     */
    setModel() {
      const { obj, prop, EMPTY, validValues } = this
      const value = +`${obj[prop]}`
      this.model = validValues.includes(value) ? value : EMPTY
    },

    /**
     * 获取最终回传值 (可覆盖)
     */
    getValue() {
      const { model, string } = this
      return string ? (model ? `${model}` : '') : model
    },
  },
}
</script>
